import { invoke } from "@tauri-apps/api/core";
import { retryOperation } from "../utils";
import { HomeLink, HomeLinkResponse, HomeList, HomeListApp } from "@/types/home";

export const getHomeLinks = async (): Promise<HomeLink[]> => {
  try {
    const links = await retryOperation(async () => {
      const result = await invoke<HomeLinkResponse[]>("get_home_links");
      // 将返回数据中的 url 字段转换为 linkUrl
      return result.map(link => ({
        ...link,
        linkUrl: link.url,
        url: undefined
      }));
    });
    return links;
  } catch (error) {
    console.error("获取主页链接列表失败:", error);
    throw new Error("获取主页链接列表失败");
  }
};

export const getHomeLists = async (): Promise<HomeList[]> => {
  try {
    return await retryOperation(async () => {
      return await invoke<HomeList[]>("get_home_lists");
    });
  } catch (error) {
    console.error("获取首页列表失败:", error);
    throw new Error("获取首页列表失败");
  }
};

export const getListApps = async (jsonUrl: string): Promise<HomeListApp[]> => {
  try {
    return await retryOperation(async () => {
      return await invoke<HomeListApp[]>("get_home_list_apps", { jsonUrl });
    });
  } catch (error) {
    console.error("获取列表应用数据失败:", error);
    throw new Error("获取列表应用数据失败");
  }
};